<?php
namespace App\Services;

use App\Models\Comment;
use App\Models\Drivers;
use Illuminate\Support\Facades\DB;

class PassengerCommentService extends BaseService
{


    /**
     * 添加评论
     * @param object $order 订单
     * @param int $score 评分
     * @return Comment
     * @throws \App\Exceptions\BobException
     */
    public function create(object $order, int $score)
    {
        DB::beginTransaction();
        $comment_model                  = new Comment();
        $comment_model->company_id      = (int)$order->company_id;
        $comment_model->order_id        = (int)$order->id;
        $comment_model->user_id         = (int)$order->user_id;
        $comment_model->driver_id       = (int)$order->driver_id;
        $comment_model->service_id      = (int)$order->service_id;
        $comment_model->service_type_id = (int)$order->service_type_id;
        $comment_model->score           = $score;
        $comment_model->type            = $order->type;
        if( !$comment_model->save() )
            return_bob('系统繁忙', 0, 200);

        $order->status       = '6';
        $order->comment_time = time();
        if( $order->save() === false ) {
            DB::rollBack();
            return_bob('系统繁忙', 0, 200);
        }

        //更新司机评论
        $driver_score = Comment::query()->where('driver_id', $order->driver_id)->avg('score');

        Drivers::query()
            ->where('id', $order->driver_id)
            ->update(['score'=> $driver_score]);

        DB::commit();

        return $comment_model;
    }

}
